<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="餐馆" prop="resId">
        <el-select
            v-model="queryParams.resPackage.resId"
            placeholder="请选择餐馆"
            clearable
            style="width: 200px"
        >
          <el-option
              v-for="resinfo in resinfoList"
              :key="resinfo.resId"
              :label="resinfo.resName"
              :value="resinfo.resId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="respakdishList"
      row-key="treeId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="套餐" align="center" prop="treeName" />
      <el-table-column label="重量" align="center" prop="resDish.weight" />
      <el-table-column label="价格" align="center" prop="resDish.price" />
      <el-table-column label="总价" align="center" prop="resPackage.unitPrice" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="scope.row.level === 3" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:respakdish:edit']">修改</el-button>
          <el-button v-if="scope.row.level === 2" link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:respakdish:add']">新增</el-button>
          <el-button v-if="scope.row.level === 3" link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:respakdish:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜品管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="respakdishRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="treeName">
          <el-input v-model="form.treeName" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="重量" prop="resDish.weight">
          <el-input v-model="form.resDish.weight" placeholder="请输入菜品重量" />
        </el-form-item>
        <el-form-item label="价格" prop="resDish.price">
          <el-input v-model="form.resDish.price" placeholder="请输入菜品价格" />
        </el-form-item>
        <el-form-item label="菜品分类" prop="resDish.dishCategoryId">
          <el-select v-model="form.resDish.dishCategoryId" placeholder="请选择菜品分类">
            <el-option
                v-for="dict in res_dish_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Respakdish">
import {
  listRespakdish,
  getRespakdish,
  delRespakdish,
  addRespakdish as addRespakdishApi,
  updateRespakdish as updateRespakdishApi,
  listRespakdish1,
  listRespakdish2
} from "@/api/system/respakdish"
import {addResdish, listResdish, updateResdish} from "@/api/system/resdish";
import {onMounted, ref} from "vue";
import {listResinfo} from "@/api/system/resinfo.js";
import { getRespackage, updateRespackage } from "@/api/system/respackage"

import useUserStore from "@/store/modules/user.js";

const userStore = useUserStore()
console.log(userStore)

const { proxy } = getCurrentInstance()
const { res_dish_type } = proxy.useDict('res_dish_type')

const respakdishList = ref([])
const respakdishOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const isExpandAll = ref(true)
const refreshTable = ref(true)
const resinfoList = ref([])

const data = reactive({
  form: {},
  queryParams: {
    relationId: null,
    treeName: null,
    pId: null,
    field: null,
    resPackage: {
      packageName: null,
      imgUrl: null,
      unitPrice: null,
      discount: null,
      packageDesc: null,
      salesVolume: null,
      resId: null,
      validPeriod: null,
      field: null,
    },
    resDishCategory: {
      categoryName: null
    },
    resDish: {
      dishName: null,
      weight: null,
      price: null,
      dishCategoryId: null
    }
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询菜品管理列表 */
function getList() {
  loading.value = true;
  const userId = userStore.id;
  const resId = queryParams.value.resPackage.resId;
  // 提取 resId 到顶级参数
  const newQueryParams = {
    ...queryParams.value,
    resId
  };
  delete newQueryParams.resPackage; // 删除原有的 resPackage 对象

  if (resId) {
    console.log('resId:', resId);
    listRespakdish1(newQueryParams).then(response => {
      const treeData = proxy.handleTree(response.data, "treeId", "pId");
      // 递归标记所有节点的层级
      markNodeLevels(treeData, 1);
      respakdishList.value = treeData;
      loading.value = false;
      console.log('respakdishList.value:', respakdishList.value);
    });
  } else {
    if (userId && userId !== 1) {
      const newQueryParams1 = {
        ...queryParams.value,
        userId
      };
      delete newQueryParams1.resPackage;
      console.log('userId:', userId)
      listRespakdish2(newQueryParams1).then(response => {
        const treeData = proxy.handleTree(response.data, "treeId", "pId");
        // 递归标记所有节点的层级
        markNodeLevels(treeData, 1);
        respakdishList.value = treeData;
        loading.value = false;
        console.log('respakdishList.value:', respakdishList.value);
      });
    }else {
      listRespakdish(newQueryParams).then(response => {
        const treeData = proxy.handleTree(response.data, "treeId", "pId");
        // 递归标记所有节点的层级
        markNodeLevels(treeData, 1);
        respakdishList.value = treeData;
        loading.value = false;
        console.log('respakdishList.value:', respakdishList.value);
      });
    }
  }
}

/** 递归标记节点层级 */
function markNodeLevels(nodes, level) {
  nodes.forEach(node => {
    node.level = level;
    if (node.children && node.children.length > 0) {
      markNodeLevels(node.children, level + 1);
    }
  });
}

/** 查询菜品管理下拉树结构 */
function getTreeselect() {
  listRespakdish().then(response => {
    respakdishOptions.value = []
    const data = { treeId: 0, treeName: '顶级节点', children: [] }
    data.children = proxy.handleTree(response.data, "treeId", "pId")
    respakdishOptions.value.push(data)
  })
}
	
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    treeId: null,
    relationId: null,
    treeName: null,
    pId: null,
    field: null,
    resPackage: {
      packageName: null,
      imgUrl: null,
      unitPrice: null,
      discount: null,
      packageDesc: null,
      salesVolume: null,
      resId: null,
      validPeriod: null,
      field: null,
    },
    resDishCategory: {
      categoryName: null
    },
    resDish: {
      dishName: null,
      weight: null,
      price: null,
      dishCategoryId: null
    }
  }
  proxy.resetForm("respakdishRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  const dishCategoryId = row.resDishCategory.dishCategoryId
  console.log('row:', row)
  reset()
  getTreeselect()
  form.value.resDish.dishCategoryId = dishCategoryId
  if (row != null && row.treeId) {
    form.value.pId = row.treeId
    // 设置新增节点的级别为父节点级别+1
    if (row.level !== undefined) {
      form.value.level = row.level + 1;
    }
  } else {
    form.value.pId = 0
    form.value.level = 1;
  }
  open.value = true
  title.value = "添加菜品管理"
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

// 添加一个计算属性来判断当前节点级别
const currentNodeLevel = computed(() => {
  if (form.value && form.value.level !== undefined) {
    return form.value.level;
  }
  return null;
});

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  await getTreeselect()
  if (row != null) {
    form.value.pId = row.pId
    // 复制节点级别信息
    if (row.level !== undefined) {
      form.value.level = row.level;
    }
  }
  getRespakdish(row.treeId).then(response => {
    // 确保从API获取的数据也包含级别信息
    if (response.data && response.data.level !== undefined) {
      form.value.level = response.data.level;
    }
    form.value = response.data
    open.value = true
    title.value = "修改菜品管理"
  })
}

/** 提交按钮 */
async function submitForm() {
  proxy.$refs["respakdishRef"].validate(async valid => {
    if (valid) {
      if (form.value.treeId != null) {
        try {
          // 查询当前菜品pid对应的菜品分类数据
          const categoryResponse = await getRespakdish(form.value.pId);
          const parentCategory = categoryResponse.data;

          if (!parentCategory) {
            console.log('未找到当前菜品的父级分类数据');
            // 继续执行原逻辑或终止操作，根据业务需求决定
          } else {
            // 获取该分类的pId（父级的父级ID）
            const grandParentId = parentCategory.pId;

            // 查询所有pId等于grandParentId的菜品分类
            const siblingsResponse = await listRespakdish({ pId: grandParentId });
            const siblingCategories = siblingsResponse.data || [];

            // 查找relationId等于当前菜品dishCategoryId的分类
            const targetCategory = siblingCategories.find(
                category => category.relationId === form.value.resDish.dishCategoryId
            );

            // 如果找到，将其treeId赋值给form.value.pId
            if (targetCategory) {
              form.value.pId = targetCategory.treeId;
              console.log('新的form.value.pId:', form.value.pId);
            } else {
              console.log('未找到匹配的菜品分类，使用原始pId:', form.value.pId);
            }
          }
        } catch (error) {
          console.error('获取菜品分类数据失败:', error);
          // 错误处理，可根据需求添加提示
        }

        // 调用当前页面的修改操作
        console.log('form.value.pId:', form.value.pId)
        await updateRespakdishApi(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });

        // 更新 respakdishList.value 中的数据
        const updateNode = (nodes) => {
          for (const node of nodes) {
            if (node.treeId === form.value.treeId) {
              // 更新节点数据
              Object.assign(node, form.value);
              return true;
            }
            if (node.children && node.children.length > 0) {
              if (updateNode(node.children)) return true;
            }
          }
          return false;
        };
        updateNode(respakdishList.value);

        // 获取当前菜品所属的套餐ID
        const packageId = findPackageIdForDish(respakdishList.value, form.value.treeId);

        if (packageId) {
          // 计算套餐新价格
          const newPrice = calculatePackagePrice(packageId);

          // 更新套餐价格
          updatePackagePrice(packageId, newPrice);
        }

        open.value = false;
        getList();

        // 调用 resdish.js 中的修改操作
        const resdishData = {
          dishId: form.value.resDish.dishId,
          dishName: form.value.treeName,
          weight: form.value.resDish.weight,
          price: form.value.resDish.price,
          dishCategoryId: form.value.resDish.dishCategoryId
        };
        updateResdish(resdishData).then(response => {
          console.log('菜品信息修改成功', response);

        });
      } else {
        // 调用 resdish.js 中的新增操作
        const resdishData = {
          dishName: form.value.treeName,
          weight: form.value.resDish.weight,
          price: form.value.resDish.price,
          dishCategoryId: form.value.resDish.dishCategoryId
        };
        addResdish(resdishData).then(response => {
          console.log('菜品信息新增成功', response);

          // 调用 listResdish 方法获取所有菜品列表
          listResdish({pageNum: 1, pageSize: 100000}).then(listResponse => {
            console.log('listResponse:', listResponse)
            const dishList = listResponse.rows;
            console.log('dishList:', dishList)
            if (dishList.length > 0) {
              // 获取列表的最后一项菜品数据的 dishId 的值
              const dishId = dishList[dishList.length - 1].dishId;
              // 将 dishId 赋值给 relationId
              form.value.relationId = dishId;
              form.value.treeName = form.value.treeName;

              // 调用当前页面的新增操作
              addRespakdishApi(form.value).then(response => {
                proxy.$modal.msgSuccess("新增成功");
                open.value = false;
                getList();
              });
            } else {
              console.log('未获取到菜品列表');
            }
          }).catch(error => {
            console.error('获取菜品列表失败', error);
            proxy.$modal.msgError("获取菜品列表失败");
          });
        }).catch(error => {
          console.error('菜品信息新增失败', error);
          proxy.$modal.msgError("菜品信息新增失败");
        });
      }
    }
  });
}

// 查找菜品所属套餐ID
function findPackageIdForDish(treeData, treeId) {
  let packageId = null;

  const findNode = (nodes) => {
    for (const node of nodes) {
      // 如果找到当前菜品节点
      if (node.treeId === treeId) {
        // 向上查找套餐节点 (level=1)
        let parent = node;
        while (parent && parent.level !== 1) {
          parent = findParentNode(treeData, parent.pId);
        }
        if (parent && parent.level === 1) {
          packageId = parent.relationId;
        }
        return true;
      }

      // 递归查找子节点
      if (node.children && node.children.length > 0) {
        if (findNode(node.children)) return true;
      }
    }
    return false;
  };

  findNode(treeData);
  return packageId;
}

// 查找父节点
function findParentNode(nodes, pId) {
  for (const node of nodes) {
    if (node.treeId === pId) {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const found = findParentNode(node.children, pId);
      if (found) return found;
    }
  }
  return null;
}

// 计算套餐新价格
function calculatePackagePrice(packageId) {
  // 1. 找到套餐节点
  const packageNode = findPackageNode(respakdishList.value, packageId);
  if (!packageNode) return 0;

  // 2. 递归计算套餐下所有菜品的总价
  let totalPrice = 0;
  const calculate = (nodes) => {
    for (const node of nodes) {
      if (node.level === 3) { // 菜品节点
        const price = parseFloat(node.resDish?.price) || 0;
        totalPrice += price;
      }
      if (node.children && node.children.length > 0) {
        calculate(node.children);
      }
    }
  };

  calculate(packageNode.children);
  return totalPrice;
}

// 查找套餐节点
function findPackageNode(nodes, packageId) {
  for (const node of nodes) {
    // 套餐节点的relationId就是packageId
    if (node.relationId === packageId && node.level === 1) {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const found = findPackageNode(node.children, packageId);
      if (found) return found;
    }
  }
  return null;
}

// 更新套餐价格
function updatePackagePrice(packageId, newPrice) {
  // 1. 获取套餐当前数据
  getRespackage(packageId).then(response => {
    const packageData = response.data;

    // 2. 更新价格
    packageData.unitPrice = newPrice;

    // 3. 调用套餐更新API
    updateRespackage(packageData).then(() => {
      console.log(`套餐 ${packageId} 价格更新为 ${newPrice} 成功`);

      // 添加回调刷新列表
      getList();
    }).catch(error => {
      console.error('更新套餐价格失败:', error);
    });
  }).catch(error => {
    console.error('获取套餐数据失败:', error);
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除菜品管理编号为"' + row.treeId + '"的数据项？').then(function() {
    return delRespakdish(row.treeId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

onMounted(() => {
  const userId = userStore.id;
  if (userId && userId !== 1) {
    listResinfo({userId}).then(response => {
      resinfoList.value = response.rows
    })
  }else {
    listResinfo().then(response => {
      resinfoList.value = response.rows
    })
  }
})

getList()
</script>
